package com.ruoyi.doc.service.impl;

import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.ofbiz.OfbizBaseService;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.doc.service.IDictService;
import org.apache.ofbiz.base.util.UtilGenerics;
import org.apache.ofbiz.entity.GenericValue;
import org.apache.ofbiz.service.GenericServiceException;
import org.apache.ofbiz.service.LocalDispatcher;
import org.apache.ofbiz.service.ServiceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class DictServiceImpl extends OfbizBaseService implements IDictService {

    private static final Logger log = LoggerFactory.getLogger(DictServiceImpl.class);

    @Override
    public List<SysDictData> selectDictDataByRemote(String remoteParms) {
        LocalDispatcher dispatcher = getDispatcher();
        if(StringUtils.isEmpty(remoteParms)){
            return Collections.emptyList();
        }
        List<SysDictData> dictDataList = new ArrayList<>();
        Map<String, Object> context = new HashMap<>();
        String[] aryParam = remoteParms.split(",");
        context.put("entityName",aryParam[0]);
        context.put("key",aryParam[1]);
        context.put("value",aryParam[2]);

        Map<String, Object> returnMap = null;
        try {
            returnMap = dispatcher.runSync("getDictData", context);
        } catch (GenericServiceException e) {
            log.error("getDictData Error", e);
            return Collections.emptyList();
        }
        if(ServiceUtil.isSuccess(returnMap)){
            List<GenericValue> dictList = UtilGenerics.checkList(returnMap.get("dictList"));
            Iterator<? extends GenericValue> gValueIter = dictList.iterator();
            while (gValueIter.hasNext()) {
                GenericValue gValue = gValueIter.next();
                if (gValue.isEmpty()) {
                    continue;
                }
                SysDictData sysDictData = new SysDictData();
                sysDictData.setDictLabel((String) gValue.get(context.get("value")));
                sysDictData.setDictValue((String)gValue.get(context.get("key")));
                dictDataList.add(sysDictData);

            }
        }
        return dictDataList;
    }
}
